package com.example.sys.log.service;

import com.example.core.po.BasePo;
import com.example.core.service.BaseCoreServiceImpl;
import com.example.core.utils.IPUtils;
import com.example.core.utils.UserUtils;
import com.example.core.vo.BaseVo;
import com.example.sys.log.dao.SysLogDao;
import com.example.sys.log.enums.SysLogMethod;
import com.example.sys.log.po.ISysLog;
import com.example.sys.log.po.SysLog;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class SysLogServiceImpl extends BaseCoreServiceImpl<SysLogDao, SysLog> implements SysLogService {

    @Override
    public void save(BasePo po) throws Exception {
        this.addLog(po, SysLogMethod.ADD);
    }

    @Override
    public void update(BasePo po) throws Exception {
        this.addLog(po, SysLogMethod.UPDATE);
    }

    @Override
    public void delete(BasePo po) throws Exception {
        this.addLog(po, SysLogMethod.DELETE);
    }

    @Override
    public void toVo(BasePo po, BaseVo vo) throws Exception {
        this.addLog(po, SysLogMethod.SELECT);
    }

    @Override
    public void addLog(BasePo po, SysLogMethod sysLogMethod) {
        if (po instanceof ISysLog) {
            SysLog sysLog = new SysLog();
            sysLog.setCreateTime(new Date());
            sysLog.setUpdateTime(new Date());
            sysLog.setModelId(po.getId());
            sysLog.setModelName(po.getClass().getName());
            sysLog.setElementId(UserUtils.getUserId());
            sysLog.setElementName(UserUtils.getUserName());
            sysLog.setMethod(sysLogMethod.getValue());
            sysLog.setIp(IPUtils.getIpAddress());
            save(sysLog);
        }
    }
}
